package com.zjc.code.algorithm.my;

/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-07-24  11:22
 */
public class Code04_BsExist {
    public static boolean exist(int[] sortedArr, int target) {
        int left = 0;
        int right = sortedArr.length - 1;
        int mid = 0;
        System.out.println("准备查找：" + target);
        while (left <= right) {
//            mid = (right + left) / 2; // 可能溢出，不推荐使用
            mid = left + ((right - left) >> 1);
            System.out.println("mid:" + mid);
            if (sortedArr[mid] == target) {
                System.out.println(target + "存在\n");
                return true;
            } else if (target > sortedArr[mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        System.out.println(target + "不存在\n");
        return false;
    }

    public static void main(String[] args) {
        int[] sortedArr = {1, 2, 3, 4, 5, 6, 7};
        int[] sortedArr2 = {1, 2, 3, 4, 5, 6};
        exist(sortedArr, 6);
        exist(sortedArr, 8);
        exist(sortedArr2, 6);
        exist(sortedArr2, 8);
    }
}
